#include <QtGui/QVBoxLayout>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <QDebug>
#include "SessionListWidget.h"
#include "Const.h"
#include "SessionsManager.h"

SessionsManager::SessionsManager(AdvancedEditor *advancedEdit,QWidget *parent) : QDialog(parent) {
	advancedEditor = advancedEdit;
	
	removeSessionDialog = new QMessageBox(parent);
	removeSessionDialog->setWindowTitle(tr("Notification"));
	removeSessionDialog->setWindowIcon(QIcon(":/icons/main.png"));
	removeSessionDialog->setIconPixmap(QPixmap(":/icons/main.png"));
	removeSessionDialog->setText("<b>" + tr("Are you sure you want to remove this session?") + "</b><br>" + tr("After this actions you cannot restore this session"));
	
	removeButtonDialog = removeSessionDialog->addButton(tr("Remove"),QMessageBox::ActionRole);
	cancelButtonDialog = removeSessionDialog->addButton(tr("Cancel"),QMessageBox::ActionRole);
		
	removeSessionDialog->setDefaultButton(cancelButtonDialog);
	
	listWidget = new ListWidget;
	connect(listWidget,SIGNAL(saveSessionAs(const QString&)),this,SLOT(saveSessionAs(const QString&)));
	connect(listWidget,SIGNAL(openSession(const QString&)),this,SLOT(openSession(const QString&)));
	connect(listWidget,SIGNAL(removeSession(const QString&)),this,SLOT(removeSession(const QString&)));
	connect(listWidget,SIGNAL(startNewSession()),this,SLOT(startNewSession()));

	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addWidget(listWidget);
	mainLayout->setContentsMargins(0,0,0,0);
	setLayout(mainLayout);
	
	setMinimumSize(sizeHint());
	
	setWindowTitle(tr("Sessions Manager") + " - Vialinx Editor");
	setWindowIcon(QIcon(":/icons/main.png"));
	
	pathToSessions = QDir::toNativeSeparators(QDir::homePath() + "/.config/sessions/");
	if (!QDir(pathToSessions).exists()) {
		QDir().mkpath(pathToSessions);
		QFile defaultSessionFile(pathToSessions + "Default Session");
		defaultSessionFile.open(QIODevice::WriteOnly);
		defaultSessionFile.close();
	}
	listWidget->addItem("Default Session");
	foreach (QString sessionName,QDir(pathToSessions).entryList(QDir::Files))
		if (sessionName != "Default Session")
			listWidget->addItem(sessionName);
	
	
	QSettings settings(ORGANIZATION,PROGRAM_NAME);
	int actionWhenStart = settings.value("Settings/WhenTheProgramStartAction",2).toInt();
	if (actionWhenStart == 0)
		exec();
	else if (actionWhenStart == 1) {
		QString lastOpenedSessionName = settings.value("SessionsManager/LastOpenedSession").toString();
		if (!lastOpenedSessionName.isEmpty())
			openSession(lastOpenedSessionName);
	}
}

SessionsManager::~SessionsManager() {
	delete listWidget;
	delete removeButtonDialog;
	delete cancelButtonDialog;
	delete removeSessionDialog;
}

void SessionsManager::saveSessionAs(const QString& name) {
	qDebug() << "[SessionsManager] Add session with name" << name;
	listWidget->addItem(name.trimmed());
	currentSessionName = name.trimmed();
	emit (currentSessionChanged(name));
}

void SessionsManager::openSession(const QString& sessionName) {
	if (currentSessionName == sessionName) {
		hide();
		return;
	}
	saveCurrentSession();
	hide();
	advancedEditor->clear();
	currentSessionName = sessionName;
	
	QFile file(pathToSessions + sessionName);
	file.open(QIODevice::ReadOnly);
	QTextStream stream(&file);
	while (!stream.atEnd()) {
		QString path = stream.readLine();
		advancedEditor->openFile(path);
	}
	if (advancedEditor->count() == 0)
		advancedEditor->newFile();
	
	emit (currentSessionChanged(sessionName));
	qDebug() << "[SessionsManager] Opened session with name" << sessionName;
}

void SessionsManager::removeSession(const QString& name) {
	removeSessionDialog->exec();
	if (removeSessionDialog->clickedButton() == cancelButtonDialog)
		return;
	
	qDebug() << "[SessionsManager] Remove session with name" << name;
	QFile file(pathToSessions + name);
	file.remove();
	delete listWidget->takeItem(listWidget->currentRow());
	
	if (currentSessionName == name) {
		currentSessionName.clear();
		emit (currentSessionChanged(currentSessionName));
	}
}

void SessionsManager::saveSettings() {
	QSettings settings(ORGANIZATION,PROGRAM_NAME);
	if (settings.value("Settings/SaveSessionWhenClose",true).toBool())
		saveCurrentSession();
	settings.setValue("SessionsManager/LastOpenedSession",currentSessionName);
}

void SessionsManager::saveCurrentSession() {
	if (!currentSessionName.isEmpty()) {
		QFile file(pathToSessions + currentSessionName);
		file.open(QIODevice::WriteOnly);
		QTextStream stream(&file);
		
		foreach (QString openedFilePath,advancedEditor->getAllOpenedFilePathes())
			stream << openedFilePath << '\n';
		qDebug() << "[SessionsManager] Sessions with name" << currentSessionName << "was saved";
	}
}

void SessionsManager::startNewSession() {
	saveCurrentSession();
	currentSessionName.clear();
	hide();
	advancedEditor->clear();
	advancedEditor->newFile();
}
